package substr

// Return a copy of S, copies S.Super and S.Subs. To copy S.Subs but not
//S.Super use S.Slice(0, -1)
func (s *S) Copy() *S {
	newx, news := make([][]int, len(s.Subs)), make([]byte, len(s.Super))
	for i, v := range s.Subs {
		newx[i] = []int{v[0], v[1]}
	}
	copy(news, s.Super)
	return &S{news, newx}
}

// Return a *S with j-i substrings. Does not copy s.Super.
// If j = -1 then j = len(s.Idx).
func (s *S) Slice(i, j int) *S {
	ln := len(s.Subs)
	if j == -1 {
		j = ln
	}
	new := make([][]int, j-i)
	for k, v := range s.Subs[i:j] {
		new[k] = []int{v[0], v[1]}
	}
	return &S{s.Super, new}
}

// Return the substrings as a slice of []byte or nil if there are no substrings.
// It is unsafe to mutate the individual []byte's and they may change under you
//if S.Super is altered.
func (s *S) Bytes() [][]byte {
	if len(s.Subs) == 0 {
		return nil
	}
	out := make([][]byte, len(s.Subs))
	for i, v := range s.Subs {
		out[i] = s.Super[v[0]:v[1]]
	}
	return out
}

// Returns the substrings as a slice of strings, or nil if there are no
//substrings.
func (s *S) Strings() []string {
	if len(s.Subs) == 0 {
		return nil
	}
	out := make([]string, len(s.Subs))
	for i, v := range s.Subs {
		out[i] = string(s.Super[v[0]:v[1]])
	}
	return out
}
